package gw.com.android.upgrade;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.RemoteViews;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.io.File;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.utils.ENV;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;


/**
 * 升级功能通知类
 */
public class UpgradeTool {
    private NotificationManager notificationManager;
    private Notification notification;
    private RemoteViews contentViews;
    private PendingIntent pendIntent;
    private final int NOTIFICATION_ID = 0x123;
    private String file_name = ENV.getAppName();
    private String appName = AppMain.getAppString(R.string.apk_name);
    private UpgradeTool mTool;

    private UpdateDialog updateDialog;

    /**
     * 强制更新时的弹框处理
     */
    public void forceUpgradeInfo(final String url, String versionInfo) {
        updateDialog = new UpdateDialog(AppActivities.getSingleton().currentActivity(), versionInfo, url, mUpgradeHandler, true);
        updateDialog.show();
    }

    /**
     * 正常更新时的弹框处理
     */
    public void normalUpgradeInfo(final String url, String versionInfo) {
//		String cont = "1.更新交易页面\n2.更新图标界面\n3.添加本地时区更改";
//		String url1 = "https://downapp.baidu.com/appsearch/AndroidPhone/1.0.55.238/1/1012271b/20160822180143/appsearch_AndroidPhone_1-0-55-238_1012271b.apk?responseContentDisposition=attachment%3Bfilename%3D%22appsearch_AndroidPhone_1012271b.apk%22&responseContentType=application%2Fvnd.android.package-archive&request_id=1472628330_8783187671&type=static";
//		updateDialog = new UpdateDialog(AppActivities.getSingleton().currentActivity(), cont, url1, mUpgradeHandler, false);
        if (null == updateDialog) {
            updateDialog = new UpdateDialog(AppActivities.getSingleton().currentActivity(), versionInfo, url, mUpgradeHandler, false);
            updateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    RxBus.getInstance().post(GTSConst.REPLY_POP_ADS_AFTER_UGPRADE, 0);
                }
            });
            updateDialog.show();
        }
    }

    /**
     * 下载过程中,用handler进行通知下载进度
     */
    private Handler mUpgradeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            contentViews = new RemoteViews(AppMain.getApp().getPackageName(), R.layout.notify_download_dialog);
            contentViews.setImageViewResource(R.id.icon, ENV.getAppIcon(AppMain.getApp()));
            switch (msg.what) {
                // 开始下载
                case AppUpgradeService.DOWNLOAD_BEGIN:
                    updateDialog.mProgressBar.setProgress(0);

                    initNotification();
                    contentViews.setProgressBar(R.id.download_progressbar, 100, 0, false); // 最开始时进度都为0
                    contentViews.setTextViewText(R.id.download_text_apkname, file_name); // 得到apk名字
                    contentViews.setTextViewText(R.id.download_progress_text, 0 + AppMain.getApp().getString(R.string.app_upgrade_text_percent)); // 最开始时进度都为0
                    notification.flags |= Notification.FLAG_NO_CLEAR; // 不可消除
                    notification.contentView = contentViews;
                    notification.contentIntent = pendIntent;
                    notificationManager.notify(NOTIFICATION_ID, notification);
                    break;

                // 下载中
                case AppUpgradeService.DOWNLOAD_ING:
                    updateDialog.mProgressBar.setProgress(msg.arg1);
                    updateDialog.mPerView.setText(msg.arg1 + AppMain.getApp().getString(R.string.app_upgrade_text_percent));
                    long downloadedSize = msg.getData().getLong("downloadedSize");
                    long totalSize = msg.getData().getLong("totalSize");
                    float D = (float) (downloadedSize) / 1024 / 1024;
                    float T = (float) (totalSize) / 1024 / 1024;
                    updateDialog.mCurSizeView.setText(AppMain.getApp().getString(R.string.app_upgrade_size, D, T));

                    contentViews.setProgressBar(R.id.download_progressbar, 100, msg.arg1, false); // mgs.arg1更新progress的值
                    contentViews.setTextViewText(R.id.download_progress_text, msg.arg1 + AppMain.getApp().getString(R.string.app_upgrade_text_percent)); // mgs.arg1得到进度
                    notification.flags |= Notification.FLAG_NO_CLEAR; // 不可消除
                    notification.contentView = contentViews;
                    notification.contentIntent = pendIntent;
                    notificationManager.notify(NOTIFICATION_ID, notification);
                    break;

                // 下载完成
                case AppUpgradeService.DOWNLOAD_INSTALLED:
                    contentViews.setViewVisibility(R.id.download_progressbar, View.GONE);
                    contentViews.setTextViewText(R.id.download_text_apkname, file_name); // 得到apk名字
                    contentViews.setTextViewText(R.id.download_progress_text, AppMain.getApp().getString(R.string.app_upgrade_download_success_install));
                    notification.flags |= Notification.FLAG_AUTO_CANCEL; // 可消除
                    // 定义通知栏上的跳转事件
                    pendIntent = PendingIntent.getActivity(AppMain.getApp(), notification.hashCode(), getIntentFromFile(), 0);
                    notification.contentView = contentViews;
                    notification.contentIntent = pendIntent;
                    notificationManager.notify(NOTIFICATION_ID, notification);
                    installAPK();
                    updateDialog.dismiss();
                    break;

                // 下载失败
                case AppUpgradeService.DOWNLOAD_FAIL:
                    // AppUpgradeService.isUpgradeing = false;
                    // secondNotification();
                    AppUpgradeService.isUpgradeing = false;
                    secondNotification();
                    contentViews.setViewVisibility(R.id.download_progressbar, View.GONE);
                    contentViews.setTextViewText(R.id.download_text_apkname, file_name); // 得到apk名字
                    contentViews.setTextViewText(R.id.download_progress_text, AppMain.getApp().getString(R.string.app_upgrade_downloading_error_msg));
                    notification.contentView = contentViews;
                    notification.contentIntent = pendIntent;
                    notificationManager.notify(NOTIFICATION_ID, notification);
                    break;
            }
        }

    };

    /**
     * 初始化通知栏
     */
    @SuppressWarnings("deprecation")
    private void initNotification() {
        notificationManager = (NotificationManager) AppMain.getApp().getSystemService(Context.NOTIFICATION_SERVICE);
        // notification = new
        // NotificationCompat.Builder(AppMain.getApp()).setContentTitle(AppMain.getApp().getString(R.string.app_name))
        // .setSmallIcon(R.drawable.app_icon)
        // .setWhen(System.currentTimeMillis())
        // .build();
        notification = new Notification(ENV.getAppIcon(AppMain.getApp()), AppMain.getApp().getString(R.string.app_upgrade_going_now), System.currentTimeMillis());
        contentViews = new RemoteViews(AppMain.getApp().getPackageName(), R.layout.notify_download_dialog);
        contentViews.setImageViewResource(R.id.icon, ENV.getAppIcon(AppMain.getApp()));
        pendIntent = PendingIntent.getActivity(AppMain.getApp(), notification.hashCode(), new Intent(), NOTIFICATION_ID);
        notification.contentView = contentViews;
        notification.contentIntent = pendIntent;
        notification.flags |= Notification.FLAG_AUTO_CANCEL; // 可消除
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 主要用于下载过程中不可清除通知导致下载失败或出错后通知也清除不掉引起的问题,使用两个
     * NotificationManager和Notification进行切换
     */
    @SuppressWarnings("deprecation")
    private void secondNotification() {
        if (null != notificationManager) {
            notification = null;
        }
        // notification = new
        // NotificationCompat.Builder(AppMain.getApp()).setContentTitle(AppMain.getApp().getString(R.string.app_name))
        // .setSmallIcon(R.drawable.app_icon)
        // .setWhen(System.currentTimeMillis())
        // .build();
        contentViews = new RemoteViews(AppMain.getApp().getPackageName(), R.layout.notify_download_dialog);
        contentViews.setImageViewResource(R.id.icon, ENV.getAppIcon(AppMain.getApp()));
        notification = new Notification(ENV.getAppIcon(AppMain.getApp()), AppMain.getApp().getString(R.string.app_upgrade_going_now), System.currentTimeMillis());
        pendIntent = PendingIntent.getActivity(AppMain.getApp(), notification.hashCode(), new Intent(), NOTIFICATION_ID);
        notification.contentView = contentViews;
        notification.contentIntent = pendIntent;
        notification.flags |= Notification.FLAG_AUTO_CANCEL; // 可消除
    }

    /**
     * 清除通知栏
     */
    private void destroyNotification() {
        if (null != notificationManager) {
            notificationManager.cancel(NOTIFICATION_ID);
            notificationManager = null;
        }

        if (null != notification) {
            notification = null;
        }
    }

    /**
     * 开启apk安装界面
     */
    public void installAPK() {
        File appFile = new File(GTConfig.instance().getRootDirectory() + "/" + appName);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(AppMain.getApp(), AppMain.getApp().getPackageName() + ".provider", appFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
        }
        Activity mCurActivity = AppActivities.getSingleton().currentActivity();
        if (null != mCurActivity && !mCurActivity.isFinishing()) {
            destroyNotification();
            mCurActivity.startActivity(intent);
        }
    }

    /**
     * 根据文件路径跳转Intent
     *
     * @return Intent
     */
    public Intent getIntentFromFile() {
        File appFile = new File(GTConfig.instance().getRootDirectory() + "/" + appName);
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        if (!appFile.exists()) {
            return installIntent;
        }
        try {
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            installIntent.setAction(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uri = FileProvider.getUriForFile(AppMain.getApp(), AppMain.getApp().getPackageName() + ".provider", appFile);
                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                installIntent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            }
            return installIntent;
        } catch (Exception e) {
            Logger.e(e);
        }
        return installIntent;
    }

}
